package registration;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public class TelephoneNumber {

    private final String number;

    public String getNumber() {
        return number;
    }

    public TelephoneNumber(String number) throws jakarta.validation.ValidationException {
        if (null == number) {
            throw new jakarta.validation.ValidationException("number不能为空");
        } else if (!isValid(number)) {
            throw new jakarta.validation.ValidationException("number格式错误");
        }
        this.number = number;
    }

    public String getAreaCode() {
        for (int i = 0; i < number.length(); i++) {
            String prefix = number.substring(0, i);
            if (isAreaCode(prefix)) {
                return prefix;
            }
        }
        return null;
    }

    private static boolean isAreaCode(String prefix) {
        final Set<String> areas = new HashSet<>(Arrays.asList("0571", "021", "010"));
        return areas.contains(prefix);
    }

    public static boolean isValid(String number) {
        String pattern = "^0?[1-9]\\d{1,2}-?\\d{8}$";
        return number.matches(pattern);
    }

}
